package com.example.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.entity.hz.Znx;
import com.example.mapper.ZnxMapper;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/api/websocket/{userId}")
@Component
public class WebSocketMessage {   // 每创建一个连接都会创建一个WebSocketMessage的对象

    private static Logger l = LoggerFactory.getLogger(WebSocketMessage.class);
    private String userId;

    /**
     * 用来解决webSocket中无法注入mapper
     */
    private static ApplicationContext applicationContext;


    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketMessage.applicationContext = applicationContext;
    }

    private static ConcurrentHashMap<String, List<Session>> sessionMap = new ConcurrentHashMap();

//    private static your_serviceimpl ns;
    //通过类注入的方式注入service类
//    @Autowired
//    public void setWaitServiceImpl(ZnxService noticeService) {
//        WebSocketMessage.ns = noticeService;
//    }

    //开启连接
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) throws IOException {
        this.userId = userId;

        List<Session> sessionList = sessionMap.get(userId);
        if(sessionList == null) sessionList = new ArrayList<>();
        System.out.println("连接成功1 " + session.getId() + " , " + userId + ": + " + sessionList.size());
        sessionList.add(session);
        sessionMap.put(userId, sessionList);
        System.out.println("连接成功2 " + session.getId() + " , " + userId + ": + " + sessionList.size());
        ZnxMapper znxMapper = applicationContext.getBean(ZnxMapper.class);
        Integer count = znxMapper.selectCount(new LambdaQueryWrapper<Znx>().eq(Znx::getNotificationCode, userId).eq(Znx::getStatus, 0));
        if(count != null && count > 0) {
            sendMessage(userId, count.toString());
        }
    }
    //关闭连接
    @OnClose
    public void onClose(Session session, @PathParam("userId") String userId) {
        System.out.println("LOG : " + session);
        List<Session> sessions = sessionMap.get(userId);
        System.out.println("LEN1 " + session.getId() + " , " + userId + "= " + sessions.size());
        if(sessions != null) sessions.remove(session);
        System.out.println("LEN2 " + session.getId() + " , " + userId + "= " + sessions.size());
//        log.info("连接关闭");
        System.out.println("连接关闭...");
    }
    //接受前端的消息
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("收到的消息:" + message);
//        session.getBasicRemote().sendText("范德萨");
    }
    @SendToUser
    // 群发消息
    public static void sendMessage(String message) throws IOException {
        try {
            //通过遍历SessionMap广播(发送)消息给所有端口
            for (List<Session> sessions : sessionMap.values()) {
                for(Session session : sessions) {
                    if(session == null) continue;
                    session.getBasicRemote().sendText(message);
                }
            }
        }catch (IOException e){
            throw e;
        }
    }

    @SendToUser
    // 群发消息
    public static void sendMessage(List<String> userList) throws IOException {
        try {
            for(String user : userList) {
                List<Session> sessions = sessionMap.get(user);
                if(sessions == null) continue;
                for(Session session : sessions) {
                    if(session == null) continue;
                    session.getBasicRemote().sendText("(0.0)");
                }
            }
        }catch (IOException e){
            throw e;
        }
    }

    @SendToUser
    public static void sendMessage(List<String> userList, String message) throws IOException {
        try {
            for(String user : userList) {
                List<Session> sessions = sessionMap.get(user);
                if(sessions == null) continue;
                for(Session session : sessions) {
                    if(session == null) continue;
                    session.getBasicRemote().sendText(message);
                }
            }
        }catch (IOException e){
            throw e;
        }
    }

    @SendToUser
    public static void sendMessage(String user, String message) throws IOException {
        try {
            List<Session> sessions = sessionMap.get(user);
            if(sessions == null) return;
            for(Session session : sessions) {
                if(session == null) continue;
                session.getBasicRemote().sendText(message);
            }
        }catch (IOException e){
            throw e;
        }
    }

}